import {loginByMobile, loginBySocial,loginByUsername} from '@/api/login'

const user = {
	state: {
	  userInfo: {},
	  permissions: [],
	  roles: [],
	  menu: [],
	  menuAll: [],
	  expires_in: '',
	  access_token: '',
	  refresh_token: ''
	},
	actions: {
	  // 根据用户名登录
	  LoginByUsername({commit}, userInfo) {
	    const user = encryption({
	      data: userInfo,
	      key: 'pigxpigxpigxpigx',
	      param: ['password']
	    })
	    return new Promise((resolve, reject) => {
	      loginByUsername(user.username, user.password, user.code, user.randomStr).then(response => {
	        const data = response.data
	        commit('SET_ACCESS_TOKEN', data.access_token)
	        commit('SET_REFRESH_TOKEN', data.refresh_token)
	        commit('SET_EXPIRES_IN', data.expires_in)
	        commit('SET_USER_INFO', data.user_info)
	        commit('SET_PERMISSIONS', data.user_info.authorities || [])
	        commit('CLEAR_LOCK')
	        resolve()
	      }).catch(error => {
	        reject(error)
	      })
	    })
	  },
    // 根据手机号登录
    LoginByPhone({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        loginByMobile(userInfo.mobile, userInfo.code).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('SET_USER_INFO', data.user_info)
          commit('SET_PERMISSIONS', data.user_info.authorities || [])
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 根据OpenId登录
    LoginBySocial({commit}, param) {
      return new Promise((resolve, reject) => {
        loginBySocial(param.state, param.code).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('SET_USER_INFO', data.user_info)
          commit('SET_PERMISSIONS', data.user_info.authorities || [])
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
	}
}

export default user
